package com.dwxt.sport.service;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.IntegralCategory;
import com.dwxt.common.util.DateUtils;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.common.util.PartyUtil;
import com.dwxt.sport.dao.RunRecordMapper;
import com.dwxt.sport.entity.RunRecord;
import com.dwxt.sport.entity.RunRecordExample;
import com.dwxt.sport.entity.vo.RunRecordVO;
import com.dwxt.sport.service.feign.UserService;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RunRecordService {
    @Autowired
    private RunRecordMapper runRecordMapper;

    @Autowired
    private UserService userService;

    public void increaseRunRecord(RunRecord runRecord) {
        int year = DateUtils.getYear(null);
        int month = DateUtils.getMonth(null);
        int day = DateUtils.getDay(null);
        RunRecord record = selectMonthOrDayRunRecord(PartyUtil.getCurrentUserId(), year, month, day);
        if (record == null) {
            runRecord.setUserId(PartyUtil.getCurrentUserId());
            runRecord.setYear(year);
            runRecord.setMonth(month);
            runRecord.setDay(day);
            runRecordMapper.insertSelective(runRecord);
        } else {
            record.setCalories(record.getCalories() + runRecord.getCalories());
            record.setDistance(record.getDistance() + runRecord.getDistance());
            record.setStepCount(record.getStepCount() + runRecord.getStepCount());
            record.setUseTime(record.getUseTime() + runRecord.getUseTime());
            record.setUpdateTime(null);
            runRecordMapper.updateByPrimaryKeySelective(record);
        }
    }

    public RunRecord selectMonthOrDayRunRecord(String currentUserId, Integer year, Integer month, Integer day) {
        //日记录
        if (day != null) {
            RunRecordExample example = new RunRecordExample();
            example.createCriteria().andUserIdEqualTo(currentUserId).andYearEqualTo(year).andMonthEqualTo(month).andDayEqualTo(day);
            List<RunRecord> runRecords = runRecordMapper.selectByExample(example);
            if (runRecords.size() > 0) {
                RunRecord runRecord = runRecords.get(0);
                double i = (double) runRecord.getCalories() / 5000;
                double rate = Double.valueOf(String.format("%.2f", i));
                if (rate > 1) {
                    rate = 1.00;
                }
                RunRecordVO runRecordVO = JsonUtils.jsonToPojo(JsonUtils.objectToJson(runRecord), RunRecordVO.class);
                runRecordVO.setRate(rate);
                return runRecordVO;
            } else {
                return null;
            }
        } else {
            //月记录
            return runRecordMapper.selectMonthRunRecord(currentUserId, year, month);
        }

    }

    public Map<String, Object> selectCurrMonthRank() {
        //获取月度排名前10名
        List<RunRecord> runRecords = runRecordMapper.get10MonthRunRecords(DateUtils.getYear(null), DateUtils.getMonth(null));
        List<Map> runRecordVOList = runRecords.stream().map(runRecord -> {
            Map res = JsonUtils.jsonToPojo(JsonUtils.objectToJson(runRecord), Map.class);
            BaseResult baseResult = userService.selectUserByKey(runRecord.getUserId());
            Object data = baseResult.getData();
            if (data != null) {
                Map map = (Map) data;
                res.put("username", map.get("username") == null ? map.get("phone") : map.get("username"));
                res.put("headPhotoUrl", map.get("headPhotoUrl"));
            }
            return res;
        }).collect(Collectors.toList());

        //获取我的当月排名
        Integer rank = runRecordMapper.selectMeMonthRank(DateUtils.getYear(null), DateUtils.getMonth(null),
                PartyUtil.getCurrentUserId());

        Map<String, Object> result = new HashMap<>();
        result.put("me", rank);
        result.put("rank", runRecordVOList);

        return result;
    }

    public Map<String, Object> selectAllRank() {
        List<Map<String, Object>> list = runRecordMapper.select10AllRunRecords();
        List<Map<String, Object>> mapList = list.stream().map(map -> {
            BaseResult baseResult = userService.selectUserByKey(map.get("userId").toString());
            //JSONObject object = JSONObject.fromObject(baseResult.getData());
            Object res = baseResult.getData();
            if (res != null) {
                Map<String, Object> data = (Map) res;
                map.put("username", data.get("username") == null ? data.get("phone") : data.get("username"));
                map.put("headPhotoUrl", data.get("headPhotoUrl"));
            }
            return map;
        }).collect(Collectors.toList());

        Integer rank = runRecordMapper.selectMeAllRank(PartyUtil.getCurrentUserId());
        Map<String, Object> result = new HashMap<>();
        result.put("me", rank);
        result.put("rank", mapList);
        return result;
    }

    public BaseResult addIntegral() {
        return userService.updateIntegral(null, null, IntegralCategory.RUN, PartyUtil.getCurrentUserId());
    }

    public List<RunRecord> selectRecordToday() {
        RunRecordExample example = new RunRecordExample();
        example.createCriteria().andYearEqualTo(DateUtils.getYear(null)).andMonthEqualTo(DateUtils.getMonth(null)).andDayEqualTo(DateUtils.getDay(null));
        return runRecordMapper.selectByExample(example);
    }
}
